package com.workspace.js_website.service;

import com.workspace.js_website.mapper.SearchMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 页面搜索相关服务
 */

@Service
public class SearchService {

    private final SearchMapper searchMapper;

    @Autowired
    public SearchService(SearchMapper searchMapper) {
        this.searchMapper = searchMapper;
    }

    public List<Map<String, Object>> getResource(String word) {
        String str = word.replace("'", "");
        str = str.replace(" ", "");
        List<Map<String, String>> data = searchMapper.getResource(str.toUpperCase());
        return changeFormat(data);
    }

    public List<String> getKeyword(String word) {
        String str = word.replace("'", "");
        return searchMapper.getKeyword(str);
    }

    public List<Map<String, Object>> getDataBySort(String sortName) {
        List<Map<String, String>> data = searchMapper.getDataBySort(sortName);
        return changeFormat(data);
    }

    public List<Map<String, String>> getProduct(String word) {
        String str = word.replace("'", "");
        str = str.replace(" ", "");
        return searchMapper.getProduct(str.toUpperCase());
    }

    private List<Map<String, Object>> changeFormat(List<Map<String, String>> data) {
        //格式转换，例如把字符串'2,3'转换成数组[2,3]
        List<Map<String, Object>> re = new ArrayList<>();
        for (Map<String, String> d : data) {
            String[] sortStr = d.get("SORT").split(",");
            List<Integer> sortInt = new ArrayList<>();
            for (String sort : sortStr) {
                sortInt.add(Integer.parseInt(sort));
            }
            Map<String, Object> el = new HashMap<>();
            el.put("SORT", sortInt);
            el.put("NAME", d.get("NAME"));
            el.put("DESCRIBE", d.get("DESCRIBE"));
            el.put("IMAGE_URL", d.get("IMAGE_URL"));
            re.add(el);
        }
        return re;
    }
}
